package com.score.intercepter;


import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.UUID;

@ConfigurationProperties(prefix = "spring.methodlog")
@Component
@Aspect
public class LogIntercepter {

    private Logger log = LoggerFactory.getLogger(LogIntercepter.class);

    private boolean print = Boolean.TRUE;

    private  static final String TRACE_ID = "traceId";

    public void setPrint(boolean print) {
        this.print = print;
    }

    @Around("execution(public * com.qjdchina.score.controller..*.*(..)) || execution(public * com.qjdchina.score.service..*.*(..))")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        String traceId = null;
        try {
            traceId = MDC.get(TRACE_ID);
        } catch (Exception e) {
            log.error("ProvideLogIntercepter get traceId Error, 获取上游调用traceId失败");
        }
        if (StringUtils.isBlank(traceId)) {
            traceId = UUID.randomUUID().toString().replace("-", "");
            log.info("没有传递traceId，重新生成");
        }
        Long startTime = System.currentTimeMillis();
        MDC.put(TRACE_ID, traceId);
        String bizType = joinPoint.getTarget() + "." + joinPoint.getSignature().getName();
        MDC.put("bizType", bizType);
        if (print) {
            MethodLogPrintUtils.methodProcessStart(joinPoint);
        }
        try {
            //执行被拦截方法
            return joinPoint.proceed();
        } catch (Exception e) {
            log.error("异常>>>>>>>>>【" + traceId + "】>>>>>>>>>【" + e.getMessage() + "】>>>>>>>>>开始");
            log.error("异常>>>>>>>>>【" + traceId + "】>>>>>>>>>【" + e.getMessage() + "】>>>>>>>>>StackTrace", e);
            log.error("异常>>>>>>>>>【" + traceId + "】>>>>>>>>>【" + e.getMessage() + "】>>>>>>>>>结束");
            //log.error(e.getMessage(), e);
            throw e;
        } finally {
            Long endTime = System.currentTimeMillis();
            long usedTimes = endTime - startTime;
            MDC.put("bizType", bizType);
            if (print) {
                MethodLogPrintUtils.methodProcessEnd(joinPoint, usedTimes);
                MDC.put("bizType", "");
            }
        }
    }
}
